package com.sanjiaozhou.gameserver.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanjiaozhou.gameserver.model.params.LoginParam;
import com.sanjiaozhou.gameserver.model.entity.User;
import com.sanjiaozhou.gameserver.mapper.UserMapper;
import com.sanjiaozhou.gameserver.service.UserService;
import com.sanjiaozhou.gameserver.utils.BusinessResult;
import com.sanjiaozhou.gameserver.utils.DateZUtils;
import com.sanjiaozhou.gameserver.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public Object register(User user) {
        // 检查用户名是否已存在
        User existUser = this.lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (existUser != null) {
            return BusinessResult.fail("注册失败，用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setStatus(Short.valueOf("1")); // 默认启用状态

        // 保存用户
        if (save(user)) {
            return BusinessResult.success("恭喜，用户注册成功");
        }
        return BusinessResult.fail("注册失败，用户名已存在");
    }

    @Override
    public Object login(LoginParam param) {
        // 查询用户
        User user = this.lambdaQuery().eq(User::getUsername, param.getUsername()).one();

        // 验证用户和密码
        if (user == null || !passwordEncoder.matches(param.getPassword(), user.getPassword())) {
            return BusinessResult.fail("用户名或密码错误");
        }

        // 生成JWT令牌
        String token = jwtTokenUtil.generateToken(user.getUsername());
        if (StringUtils.isNotBlank(token)) {
            return BusinessResult.success(token).message("登录成功");
        }
        return BusinessResult.fail("用户名或密码错误");
    }

    @Override
    public Object logout(String token) {
        try {
            // 从令牌中获取用户名
            String userId = jwtTokenUtil.getUserIdFromToken(token);

            // 验证令牌有效性
            if (!jwtTokenUtil.validateToken(token, userId)) {
                return false;
            }

            // 将令牌添加到黑名单（Redis）
            jwtTokenUtil.invalidateToken(token);

            // 可选：删除数据库中的令牌记录
            jwtTokenUtil.cleanExpiredInvalidatedTokens();

            return BusinessResult.success("退出成功");
        } catch (Exception e) {
            log.error("Logout error: {}", e);
            return BusinessResult.fail("退出失败");
        }
    }
}